package com.lancoo.answer.view.fragment.correctmistake

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import com.lancoo.answer.databinding.EvFmtGctAnalysisBinding
import com.lancoo.answer.model.AnswerConstant
import com.lancoo.answer.model.ConstantBean
import com.lancoo.answer.model.bean.ModelAnswerArea
import com.lancoo.answer.model.bean.Ques
import com.lancoo.answer.model.bean.TextInfo
import com.lancoo.answer.util.ExamFontSizeAdjustUtils
import com.lancoo.answer.util.HtmlUtils
import com.lancoo.answer.util.RichTextUtils
import com.lancoo.answer.view.adapter.CorrectMistakesTextAdapter
import com.lancoo.answer.view.base.BaseBindingFragment
import com.lancoo.answer.widget.DrawView

/**
 * Created by wealive on 2021/9/24.
 *
 *
 */
class WrongCorrectMistakesFragment : BaseBindingFragment<EvFmtGctAnalysisBinding>() {
    private val textInfoList = mutableListOf<TextInfo>()
    private lateinit var adapter: CorrectMistakesTextAdapter
    private var GenreType = 0
    private var GenreID = 0
    private val answerArea = mutableListOf<ModelAnswerArea>()

    private lateinit var ques: Ques
    private var typeIndex = 0
    private var quesIndex = 0
    private var defaultLoadIndex = 0


    companion object {
        fun loadFragment(typeIndex: Int, quesIndex: Int, defaultLoadIndex: Int): Fragment? {
            val mBundle = Bundle()
            mBundle.putInt(AnswerConstant.KEY_TYPEINDEX, typeIndex)
            mBundle.putInt(AnswerConstant.KEY_QUESINDEX, quesIndex)
            mBundle.putInt("loadQuesIndex", defaultLoadIndex)
            val wrongCorrectMistakesFragment = WrongCorrectMistakesFragment()
            wrongCorrectMistakesFragment.arguments = mBundle
            return wrongCorrectMistakesFragment
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initAnswerData()
    }

    @SuppressLint("SetTextI18n")
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.apply {
            if (!ques.QuesIndexText.isNullOrEmpty()) {
                tvLeader.text = HtmlUtils.setText(ques.QuesIndexText!!)
                tvLeader.visibility = View.VISIBLE
            } else {
                tvLeader.visibility = View.INVISIBLE
            }
            showAnswerAnalysis()
            adapter = CorrectMistakesTextAdapter(0, requireContext(), textInfoList, answerArea)
            fl.setAdapter(adapter)
            val subItemAnswerList = ques.ModelAnswerInfoList!!

            for (i in textInfoList.indices) {
                val textInfo = textInfoList[i]
                val child = fl.getChildAt(i)
                if (answerArea.size > 1) {
                    drawArea(i)
                } else if (ques.ChildList!![0].ItemList!!.size == 1) {
                    tvIndex.text = "${ques.ChildList!![0].ItemList!![0].ItemSortIndex}."
                }
                if (textInfo.stuType != -1) {
                    var startPosition = -1
                    var endPosition = -1
                    val viewList = mutableListOf<View>()
                    if (textInfo.digitalAnswer.contains("-")) {
                        repeat(answerArea.size) {
                            startPosition =
                                textInfo.digitalAnswer.split("@|")[0].split("*|")[0].split("-")[0].toInt()
                            endPosition =
                                textInfo.digitalAnswer.split("@|")[0].split("*|")[0].split("-")[1].toInt()
                        }
                        for (j in startPosition..endPosition) {
                            viewList.add(fl.getChildAt(j))
                        }
                        drawAnswer(
                            textInfo.stuType,
                            1,
                            "本区域无错",
                            i,
                            child,
                            viewList
                        )
                    } else if (textInfo.stuType == 4) {
                        startPosition =
                            textInfo.digitalAnswer.split("@|")[0].split("*|")[0].toInt()
                        for (j in textInfoList.indices) {
                            if (startPosition == textInfoList[j].Index) {
                                viewList.add(fl.getChildAt(j))
                                drawAnswer(
                                    textInfo.stuType,
                                    1,
                                    "本区域无错",
                                    j,
                                    child,
                                    viewList
                                )
                            }
                        }
                    } else {
                        drawAnswer(
                            textInfo.stuType,
                            1,
                            textInfo.stuAnswer,
                            i,
                            child,
                            viewList
                        )
                    }
                }
            }
            try {
                for (i in subItemAnswerList.indices) {
                    val itemAnswerList =
                        subItemAnswerList[i].Answer!!.split("$|")
                    val itemPosition = itemAnswerList[0].split("*|")[0]
                    val itemType = itemAnswerList[0].split("*|")[1].toInt()
                    val itemAnswer = itemAnswerList[0].split("*|")[2]
                    if (itemPosition.contains("-")) {
                        val startPosition = itemPosition.split("-")[0].toInt()
                        val endPosition = itemPosition.split("-")[1].toInt()
                        val viewList = mutableListOf<View>()
                        textInfoList.forEachIndexed { index, textInfo ->
                            if (textInfo.Index in startPosition..endPosition) {
                                viewList.add(fl.getChildAt(index))
                            }
                        }
                        drawAnswer(
                            itemType,
                            0,
                            "本区域无错",
                            startPosition,
                            fl.getChildAt(startPosition),
                            viewList
                        )
                    } else {
                        drawAnswer(
                            itemType,
                            0,
                            if (itemType == 4) "无错" else itemAnswer,
                            getTextPosition(itemPosition.toInt()),
                            fl.getChildAt(getTextPosition(itemPosition.toInt())),
                            mutableListOf(fl.getChildAt(getTextPosition(itemPosition.toInt())))
                        )
                    }
                }
            } catch (e: Exception) {

            } finally {

            }
        }
    }

    private fun showAnswerAnalysis() {
        val analysisList =
            ques.ChildList!![0].ItemList!!
        val sbAnalysis = StringBuffer()
        for (i in analysisList.indices) {
            sbAnalysis.append(
                "${
                    if (analysisList.size <= 1) {
                        ""
                    } else {
                        (i + 1).toString() + "."
                    }
                }${analysisList[i].ItemAnalysis.let { if (it!!.isEmpty()) "...略" else it }}<br>"
            )
        }
        binding.answerAnalysisView.setAnalysis(RichTextUtils.getCorrectAnalysis(ques.ChildList!![0].ItemList))
    }

    private fun initAnswerData() {
        if (ConstantBean.constantExamBean == null) {
            return
        }
        val kindBeanList = ConstantBean.constantExamBean!!.TypeList
        typeIndex = requireArguments().getInt(AnswerConstant.KEY_TYPEINDEX)
        quesIndex = requireArguments().getInt(AnswerConstant.KEY_QUESINDEX)
        defaultLoadIndex = requireArguments().getInt("loadQuesIndex")
        ques = kindBeanList!![typeIndex].QuesList!![quesIndex]
        GenreType = ques.GenreType!!.toInt()
        GenreID = ques.GenreID!!.toInt()
        val answerAreaList =
            ques.ModelAnswerAreaList!!
        for (i in answerAreaList.indices) {
            val area = answerAreaList[i]
            answerArea.add(area)
        }
        textInfoList.addAll(ques.ModelTextInfoList!!)
    }

    /*绘制编号*/
    private fun drawArea(position: Int) {
        answerArea.forEachIndexed { index, it ->
            if (it.AnswerArea!!.split("-")[0].toInt() == textInfoList[position].Index) {
                val child = binding.fl.getChildAt(position)
                val tvIndex =
                    DrawView(
                        true,
                        false,
                        child,
                        ques.ChildList!![0].ItemList!![if (ques.ChildList!![0].ItemList!!.size > 1) index else 0].ItemSortIndex!!,
                        "",
                        -1,
                        1,
                        requireContext()
                    )
                binding.flLayout.addView(tvIndex)
            }
        }
    }

    /*绘制保存的作答*/
    @SuppressLint("UseCompatLoadingForDrawables")
    private fun drawAnswer(
        type: Int,
        color: Int,
        answer: String,
        position: Int,
        child: View,
        list: MutableList<View>
    ) {
        val isFirst = isFirstPosition(position)
        when (type) {
            0, 1, 2, 3 -> {
                val answerView =
                    DrawView(false, isFirst, child, answer, "", type, color, requireContext())
                binding.flLayout.addView(answerView)
            }
            4 -> {
                val answerView =
                    DrawView(false, isFirst, answer, "", list, type, color, requireContext())
                binding.flLayout.addView(answerView)
            }
        }
    }

    /*是否是区域第一个*/
    private fun isFirstPosition(position: Int): Boolean {
        var isFirst = false
        if (answerArea.size == 10) {
            answerArea.forEach {
                if (textInfoList[position].Index == it.AnswerArea!!.split("-")[0].toInt()) {
                    isFirst = true
                }
            }
        }
        return isFirst
    }

    /**
     * 根据index找出position
     */
    private fun getTextPosition(index: Int): Int {
        var position = -1
        textInfoList.forEachIndexed { i, textInfo ->
            if (textInfo.Index == index) {
                position = i
            }
        }
        return position
    }

    fun adjustFontSize() {
        ExamFontSizeAdjustUtils.adjustTextViewFontSize(binding.tvLeader,15)
        ExamFontSizeAdjustUtils.adjustTextViewFontSize(binding.tvIndex,15)
        binding.answerAnalysisView.adjustFontSize()
    }
}